package com.itheima.app.manager;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.DateFormatUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MovementManager {

    @Reference
    private MovementService movementService;
    @Reference
    private UserInfoService userInfoService;
    @Reference
    private CommentService commentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private MQMovementManager mqMovementManager;

    //                                 发布动态
    public void saveMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
//        //先判断发布动态是否被冻结
//        Long userId = movement.getUserId();
//        //接收一下冻结原因
//        String freezeReason = null;
//        //获取冻结原因
//        if(stringRedisTemplate.hasKey("freezeReason")){
//            freezeReason = stringRedisTemplate.opsForValue().get("freezeReason");
//        }
//        //如果redis有这个key，不允许登录
//        if(stringRedisTemplate.hasKey(userId+"loginState")){
//            throw new RuntimeException("您的账号因"+freezeReason+"发布动态已被限制，请大喊一声勇敢牛牛！不怕困难！");
//        }
        //1. 图片上传阿里云,获取访问路径集合
            //Movement对象中imageContent是一个List<String>,前端返回来的也是一个图片数组
        List<String> imageList = new ArrayList<>();
        for (MultipartFile image : imageContent) {
            //获取图片访问路径
            String imagePath = ossTemplate.upload(image.getOriginalFilename(), image.getInputStream());
            //存储整个数组中图片的访问路径
            imageList.add(imagePath);
        }

        //2. 组装一个movement对象
        movement.setId(ObjectId.get());//提前生成一个objectId
        movement.setUserId(UserHolder.get().getId());//用户id
        /*movement.setPid(0L);//todo 临时写死,一会处理*/
        movement.setMedias(imageList);//图片集合路径
        movement.setState(0);//默认为0 未审核 已对接华为云
        movement.setCreated(System.currentTimeMillis());//时间
        movement.setSeeType(1);//公开，目前项目未使用

        //3. 调用service存储movement对象
        movementService.save(movement);

        //4. 向MQ投递一个消息(审核)
        rocketMQTemplate.convertAndSend("tanhua-movement-check",movement.getId().toHexString());
        System.err.println("发送了  ！！！！！！！！！！！！！！！！！！！！！！！！！！");
        //5. 向MQ投递消息(大数据推荐)
        mqMovementManager.sendMovementMsg(movement.getId().toHexString(),MQMovementManager.MOVEMENT_PUBLISH);
    }



    //查询我的动态(优化版)
    public PageBeanVo findMyMovement(Long userId, Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        PageBeanVo pageBeanVo = movementService.findMovementByUserId(userId, pageNum, pageSize);

        //2. 封装返回结果
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                //0. 根据用户id查询用户信息
                UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());

                //1. 创建一个MovementVO
                MovementVo movementVo = new MovementVo();

                //2. 设置用户部分
                movementVo.setUserInfo(userInfo);

                //3. 设置动态部分
                movementVo.setMovement(movement);

                //判断当前用户是否对当前动态点过赞，点过喜欢
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userId, movementVo.getId()))){
                    movementVo.setHasLiked(1);
                }
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, movementVo.getId()))){
                    movementVo.setHasLoved(1);
                }
                //4. 放入list
                movementVoList.add(movementVo);
            }
        }
        pageBeanVo.setItems(movementVoList);

        return pageBeanVo;
    }

    //查询好友动态
    public PageBeanVo findFriendMovement(Integer pageNum, Integer pageSize) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 查询指定用户的好友动态
        PageBeanVo pageBeanVo = movementService.findFriendMovementByUserId(userId,pageNum,pageSize);

        //3. 封装返回结果
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                //0. 根据用户id查询用户信息
                UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());

                //1. 创建一个MovementVO
                MovementVo movementVo = new MovementVo();

                //2. 设置用户部分
                movementVo.setUserInfo(userInfo);

                //3. 设置动态部分
                movementVo.setMovement(movement);

                //判断当前用户是否对当前动态点过赞，点过喜欢
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userId, movementVo.getId()))){
                    movementVo.setHasLiked(1);
                }
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, movementVo.getId()))){
                    movementVo.setHasLoved(1);
                }
                //4. 放入list
                movementVoList.add(movementVo);
            }
        }

        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }

    //查询推荐给我的动态
    public PageBeanVo findRecommendMovement(Integer pageNum, Integer pageSize) {
        //1.获取到登录用户的id
        Long userId = UserHolder.get().getId();

        //2.调用service分页查询推荐给userId数据
        PageBeanVo pageBeanVo = movementService.findRecommendMovement(userId,pageNum,pageSize);

        //3.封装返回结果
        List<Movement> movementList = (List<Movement>)pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(movementList)){
            for (Movement movement : movementList) {
                //1.根据用户id查询用户信息
                UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());

                //2.创建一个MovenmentVo
                MovementVo movementVo = new MovementVo();

                //3.设置用户部分
                movementVo.setUserInfo(userInfo);

                //4. 设置动态部分
                movementVo.setMovement(movement);

                //判断当前用户是否对当前动态点过赞，点过喜欢
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userId, movementVo.getId()))){
                    movementVo.setHasLiked(1);
                }
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, movementVo.getId()))){
                    movementVo.setHasLoved(1);
                }

                //5.放入list
                movementVoList.add(movementVo);
            }
        }
        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }

    //动态点赞
    public Integer saveMovementLike(String movementId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();

        // 2.组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(1);
        comment.setUserId(userId);

        // 3.调用service返回点赞数
        Integer num = commentService.saveMovementComment(comment);
        // 4.将点赞标识写入redis
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userId, movementId), "1");
        // 5.向MQ发送消息(用户做了点赞操作)
        mqMovementManager.sendMovementMsg(movementId,MQMovementManager.MOVEMENT_LIKE);
        // 6.返回点赞数
        return num;
    }

    //取消点赞
    public Integer deleteMovementLike(String movementId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();

        // 2.组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(1);
        comment.setUserId(userId);

        // 3.调用service完成取消点赞后的点赞数
        Integer num = commentService.deleteMovementComment(comment);

        // 4.从redis删除点赞标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, userId, movementId));

        // 5.向MQ发送消息(用户取消了点赞)
        mqMovementManager.sendMovementMsg(movementId,MQMovementManager.MOVEMENT_DISLIKE);
        // 6.返回点赞数
        return num;
    }

    //动态喜欢
    public Integer saveMovementLove(String movementId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();

        // 2.组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(3);
        comment.setUserId(userId);

        // 3.调用service返回喜欢数
        Integer num = commentService.saveMovementComment(comment);

        // 4.将喜欢标识写入redis
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, movementId), "3");
        // 5.向MQ发送消息(用户做了喜欢操作)
        mqMovementManager.sendMovementMsg(movementId,MQMovementManager.MOVEMENT_LOVE);
        // 6.返回喜欢数
        return num;
    }

    //取消喜欢
    public Integer deleteMovementLove(String movementId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();

        // 2.组装comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(3);
        comment.setUserId(userId);

        // 3.调用service完成取消喜欢后的喜欢数
        Integer num = commentService.deleteMovementComment(comment);

        // 4.从redis删除喜欢标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, userId, movementId));

        // 5.向MQ发送消息(用户做了不喜欢操作)
        mqMovementManager.sendMovementMsg(movementId,MQMovementManager.MOVEMENT_DISLOVE);

        // 6.返回喜欢数
        return num;
    }

    //根据动态id查询动态详情
    public MovementVo findMovementById(String movementId) {
        //1.根据动态id查询动态详情
        Movement movement = movementService.findMovementById(movementId);

        //2.根据动态发布人id查询其userInfo
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoService.findByUserId(userId);

        //3.组装返回Vo(坑：下面两部分赋值,顺序不能颠倒)
        MovementVo movementVo = new MovementVo();
        movementVo.setUserInfo(userInfo);
        movementVo.setMovement(movement);

        //4.向MQ发送消息(用户做了浏览动态的操作)
        mqMovementManager.sendMovementMsg(movement.getId().toHexString(),MQMovementManager.MOVEMENT_BROWSE);
        return movementVo;
    }

    //查询动态评论区列表
    public PageBeanVo findMovementCommentList(String movementId, Integer pageNum, Integer pageSize) {
        //1.调用service查询
        PageBeanVo pageBeanVo = commentService.findMovementCommentList(movementId,pageNum,pageSize);

        //2.处理返回结果
        List<Comment> commentList = (List<Comment>)pageBeanVo.getItems();
        List<CommentVo> commentVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(commentList)){
            for (Comment comment : commentList) {
                //1.创建CommentVo对象
                CommentVo commentVo = new CommentVo();

                //2.设置用户信息
                Long userId = comment.getUserId();
                UserInfo userInfo = userInfoService.findByUserId(userId);
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());

                //3.设置评论信息
                commentVo.setId(comment.getId().toHexString());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));

                //4. vo放入临时集合
                commentVoList.add(commentVo);
            }
        }
        pageBeanVo.setItems(commentVoList);
        return pageBeanVo;
    }

    //保存语言评论
    public void saveMovementComment(String movementId, String commentContent) {
//        //判断是否被冻结发言
//        Long userId = UserHolder.get().getId();
//        //接收一下冻结原因
//        String freezeReason = null;
//        //获取冻结原因
//        if(stringRedisTemplate.hasKey("freezeReason")){
//            freezeReason = stringRedisTemplate.opsForValue().get("freezeReason");
//        }
//        //如果redis有这个key，不允许评论
//        if(stringRedisTemplate.hasKey(userId+"loginState")){
//            throw new RuntimeException("您的账号因"+freezeReason+"发布动态已被限制，请大喊一声勇敢牛牛！不怕困难！");
//        }
        //1. 准备评论对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(2);
        comment.setUserId(UserHolder.get().getId());
        comment.setContent(commentContent);

        //2.调用service保存
        commentService.saveMovementComment(comment);

        // 3.向MQ发送消息(用户做了评论操作)
        mqMovementManager.sendMovementMsg(movementId,MQMovementManager.MOVEMENT_COMMENT);
    }


    //查询我的动态(基础版)
   /*  public PageBeanVo findMyMovement(Long userId, Integer pageNum, Integer pageSize) {

        //1.调用service查询指定用户的动态信息
        PageBeanVo pageBeanVo = movementService.findMyMovement(userId,pageNum,pageSize);

        //2.封装返回结果   movement===>movementVo
        List<Movement> movementList = (List<Movement>)pageBeanVo.getItems();
        ArrayList<MovementVo> movementVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(movementList)){
            for (Movement movement : movementList) {
                //0. 根据用户id查询用户信息
                UserInfo userInfo = userInfoService.findByUserId(userId);

                //1. 创建一个MovementVO
                MovementVo movementVo = new MovementVo();

                //2. 设置用户部分
                BeanUtil.copyProperties(userInfo,movementVo);//复制了 avatar,nickname,gender,age
                //tags要从String===>String[]
                if(StringUtils.isNoneEmpty(userInfo.getTags())){
                    String[] tags = userInfo.getTags().split(",");
                    movementVo.setTags(tags);
                }

                //3. 设置动态部分
                movementVo.setId(movement.getId().toHexString());
                BeanUtil.copyProperties(movement,movementVo);//复制了 textContent  userId  likeCount commentCount loveCount
                if(CollectionUtil.isNotEmpty(movement.getMedias())){
                    //复制movement中的medias到movementVo的imageConten
                    // List<String> ==转为==>String[]
                    movementVo.setImageContent(movement.getMedias().toArray(new String[]{}));
                }
                movementVo.setDistance("1公里");
                movementVo.setCreateDate(DateFormatUtil.format(new Date(movement.getCreated())));

                //4. 放入list
                movementVoList.add(movementVo);
            }
        }
        //重新放入Items
        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }*/
}
